package com.msb.dongbao.portal.web.filter;

import com.alibaba.fastjson.JSONObject;
import com.msb.dongbao.portal.web.controller.api.CheckUtils;

import com.msb.dongbao.portal.web.util.BodyReaderHttpServletRequestWrapper;
import com.msb.dongbao.portal.web.util.HttpParamUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.SortedMap;

@Component
public class SignAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter生效了");
        //签名的验证
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletRequest request = new BodyReaderHttpServletRequestWrapper((HttpServletRequest)servletRequest);

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //整合获取参数,统一get和post 不管是url还是body
        SortedMap<String, String> allparams = HttpParamUtils.getAllparams(request);
        System.out.println("allparams=" + allparams);
        //校验签名
        boolean checkResult = CheckUtils.checkSign(allparams);
        System.out.println("校验签名结果：" + checkResult);
        if (checkResult) {
            filterChain.doFilter(request, response);
        } else {
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter writer = servletResponse.getWriter();
            JSONObject param = new JSONObject();
            param.put("code", -1);
            param.put("message", "签名错了");
            writer.append(param.toJSONString());
        }


    }

    @Override
    public void destroy() {
        System.out.println("销毁");
    }
}
